package com.jinxin.platform.cdsideparkmgr.utils;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Base64;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.security.InvalidKeyException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Formatter;

/**
 * @Author 那个男人
 * @Date 2022/9/21 16:49
 * @Version 1.0
 */
@Slf4j
public class EncryptUtil {

    private static final String HMAC_SHA1 = "HmacSHA1";

    private static String toHexString(byte[] bytes) {
        Formatter formatter = new Formatter();
        for (byte b : bytes) {
            formatter.format("%02x", b);
        }
        return formatter.toString();
    }

    private static String encrypt(String data, String key) throws NoSuchAlgorithmException, InvalidKeyException {
        SecretKeySpec secret = new SecretKeySpec(key.getBytes(), HMAC_SHA1);
        Mac mac = Mac.getInstance(HMAC_SHA1);
        mac.init(secret);
        return toHexString(mac.doFinal(data.getBytes()));
    }

    public static String getMd5(String str) {
        MessageDigest md5 = null;
        try {
            md5 = MessageDigest.getInstance("MD5");
        } catch (Exception e) {
            log.error(e.toString());
        }
        byte[] bs = md5.digest(str.getBytes());
        StringBuilder sb = new StringBuilder(40);
        for(byte x:bs) {
            if((x & 0xff)>>4 == 0) {
                sb.append("0").append(Integer.toHexString(x & 0xff));
            } else {
                sb.append(Integer.toHexString(x & 0xff));
            }
        }
        return sb.toString();
    }


    public static void main(String[] args) throws Exception {
//        String hmac = encrypt("123", "123");
//        System.out.println(hmac);
        JSONObject jsonObject  = new JSONObject();
        jsonObject.put("page",1);
        jsonObject.put("size",100);
        String str = "{\"page\":1,\"size\":100}";
        System.out.println(Base64.encodeBase64String(getMd5("blog").getBytes()));
    }
}
